import { ipcMain, BrowserWindow } from 'electron'
import axios, { AxiosRequestConfig } from 'axios'

// 创建axios实例
const httpClient = axios.create({
  timeout: 30000, // 请求超时时间
})

// 初始化请求转发功能
export function setupHttpProxy() {
  // 处理HTTP请求
  ipcMain.handle('http-request', async (event, config: AxiosRequestConfig) => {
    try {
      const response = await httpClient(config)
      return {
        success: true,
        data: response.data,
        status: response.status,
        headers: response.headers,
      }
    } catch (error: any) {
      console.error("HTTP请求错误:", error.message)

      // 检查是否是401未授权错误
      const status = error.response?.status
      const responseData = error.response?.data

      // 如果是401错误，通知渲染进程进行重定向
      if (status === 401 || responseData?.code === 401) {
        console.log("检测到401错误，通知渲染进程重定向到登录页")

        // 获取当前窗口
        const win = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0]

        if (win) {
          // 发送消息到渲染进程，通知它需要重定向到登录页
          win.webContents.send('auth-token-expired', {
            message: "登录状态已过期，请重新登录",
            status: status,
            data: responseData
          })
        }
      }

      return {
        success: false,
        error: {
          message: error.message,
          status: status,
          data: responseData,
        },
      }
    }
  })
}
